package com.qf.face.client.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author 30909
 */
public class Base64Util {

    /**
     * 图片转base64
     * Java原生类中使用 BufferedImages 来表达一个图片
     *
     * @param image 带转化的图片
     * @return 返回的Base64 编码
     */
    public static String image2Base64(BufferedImage image) {
        String base64 = null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "png", stream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        byte[] bytes = stream.toByteArray();
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 文件换 base64
     */
    public static String image2Base64(String fileName) {
        File file = new File(fileName);
        try {
            BufferedImage read = ImageIO.read(file);
            return image2Base64(read);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64 转 BufferedImage
     */
    public static BufferedImage base64ToImage(String base64) {
        //健壮性校验
        if (base64 == null && base64.length() > 0) {
            return null;
        }

        byte[] bytes = Base64.decodeBase64(base64);
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        //转流图片

        try {
            return ImageIO.read(stream);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
    /**
     * base64 转
     */
    public static BufferedImage buffered64ToImage(String base64){
        if (base64==null || base64.length() == 0 ){
            return null;
        }
        byte[] bytes = Base64.decodeBase64(base64);
        // idea 支持驼峰
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);

        try {
            return ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
